package com.huawei.chengdu.meetingdemo.view.dialogs;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.TypedValue;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;

import com.device.idea.meeting.CallCtrl.model.CallStatus;
import com.device.idea.meeting.CallCtrl.model.RealAudioInfo;
import com.device.idea.meeting.CallCtrl.model.RealVideoInfo;
import com.device.idea.meeting.Share.model.ShareCurInfo;
import com.huawei.chengdu.meetingdemo.consts.ViewNameConts;
import com.huawei.chengdu.meetingdemo.util.LogUtil;
import com.huawei.chengdu.meetingdemo.util.RelTimer;
import com.huawei.chengdu.meetingdemo.presenter.MeetingManager;
import com.huawei.chengdu.meetingdemo.R;

import java.util.Locale;
import java.util.TimerTask;

public class AdvMeetingInfoView extends BaseView {
    private static String TAG = "AdvMeetingInfoView";

    private CallStatus callStatus; // 会议信息

    private ShareCurInfo shareCurInfo; // 共享辅流状态

    private RelTimer timer = null;

    private ImageView back;

    private TextView conferenceAuxForamtUp;

    private TextView conferenceAuxForamtDown;

    private TextView conferenceAuxRatetUp;

    private TextView conferenceAuxRatetDown;

    private TextView lineRateUp;

    private TextView lineRateDown;

    private TextView mainpicFormatUp;

    private TextView mainpicFormatDown;

    private TextView videoRateUp;

    private TextView videoRateDown;

    private TextView audioProUp;

    private TextView audioProDown;

    private TextView audioRateUp;

    private TextView audioRateDown;

    private TextView videoLostrateUp;

    private TextView videoLostrateDown;

    private TextView auxLostrateUp;

    private TextView auxLostrateDown;

    private TextView audioLostrateUp;

    private TextView audioLostrateDown;

    private Chronometer confTime;

    private TextView auxToken;

    private final String zeroValue = "-- --";

    /**
     * 先获取数据
     */
    public void initData() {
        stopTimer();
        startGetConfInfoTimer();
    }

    /**
     * 刷新速率
     */
    private Handler updateHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (callStatus != null) {
                updateStatus();
            }
            if (shareCurInfo != null) {
                // 材料令牌
                updateShareStatus();
            }
        }
    };

    /**
     * 开始刷新会场列表定时器
     */
    public void startGetConfInfoTimer() {
        stopTimer();
        timer = new RelTimer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                callStatus = MeetingManager.getInstance().getCallStatus();
                shareCurInfo = MeetingManager.getInstance().getCurShareInfo();
                updateHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(task, 0, 4 * 1000);
    }

    private void stopTimer() {
        if (timer != null) {
            LogUtil.info( "stopTimer");
            timer.cancel();
            timer = null;
        }
    }

    private void updateStatus() {
        if (callStatus == null) {
            return;
        }

        // 线路速率
        lineRateUp.setText(
                String.format(Locale.ROOT, "%.2fk", callStatus.getSendLineRate() / 1000.00)); // 1966920, 1,966.92kbps
        lineRateDown.setText(
                String.format(Locale.ROOT, "%.2fk", callStatus.getRecLineRate() / 1000.00)); // 1966920, 1,966.92kbps

        // 更新视频信息：
        updateVideo();

        // 更新音频信息：
        updateAudio();

        // 更新材料信息：
        updateAux();
    }

    private void updateShareStatus() {
        switch (shareCurInfo.getShareAction()) {
            case ACTION_SENDING:
                auxToken.setText(mContext.getString(R.string.aux_token_local));
                break;
            case ACTION_RECVING:
                auxToken.setText(mContext.getString(R.string.aux_token_remote));
                break;
            default:
                auxToken.setText(mContext.getString(R.string.message_none));
                break;
        }
    }

    private void updateVideo() {
        // 发送方：
        RealVideoInfo sendVideoInfo = callStatus.getSendMainInfo().get(0);
        if (sendVideoInfo != null) {
            // 视频流图像格式 发送
            LogUtil.info( "format type" + sendVideoInfo.getWidth());
            LogUtil.info( "format type" + sendVideoInfo.getHeight());
            String picFormatUp = getVideoProtocolPostfix(sendVideoInfo);
            mainpicFormatUp.setText(picFormatUp);
            if (picFormatUp.length() > 13) {
                mainpicFormatUp.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_30));
            } else {
                mainpicFormatUp.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_35));
            }
            // 视频速率[帧率] 1966920, 1,966.92kbps
            videoRateUp.setText(
                    String.format(Locale.ROOT, "%.2fk", sendVideoInfo.getRate() / 1000.00) + "[" + sendVideoInfo.getFps()
                            + "]");

            // 视频丢包率[丢包数]  /10 % 发送
            if (sendVideoInfo.getLostPackets() > 0) {
                videoLostrateUp.setText(sendVideoInfo.getLostPer() / 10.0 + "%[" + sendVideoInfo.getLostPackets()
                        + "]");
            } else {
                videoLostrateUp.setText(zeroValue);
            }
        }

        // 接收方：
        RealVideoInfo recVideoInfo = callStatus.getRecMainInfo().get(0);
        if (recVideoInfo != null) {
            // 视频流图像格式 接收
            String picFormatDown = getVideoProtocolPostfix(recVideoInfo);
            mainpicFormatDown.setText(picFormatDown);
            if (picFormatDown.length() > 13) {
                mainpicFormatDown.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_30));
            } else {
                mainpicFormatDown.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_35));
            }
            // 视频速率[帧率] 1966920, 1,966.92kbps
            videoRateDown.setText(
                    String.format(Locale.ROOT, "%.2fk", recVideoInfo.getRate() / 1000.00) + "[" + recVideoInfo.getFps()
                            + "]");
            // 视频丢包率[丢包数]  /10 % 接收
            if (recVideoInfo.getLostPackets() > 0) {
                videoLostrateDown.setText(recVideoInfo.getLostPer() / 10.0 + "%[" + recVideoInfo.getLostPackets()
                        + "]");
            } else {
                videoLostrateDown.setText(zeroValue);
            }
        }
    }

    private void updateAudio() {
        // 发送方 音频：
        RealAudioInfo sendAudioInfo = callStatus.getSendAudioInfo();
        if (sendAudioInfo != null) {
            // 音频协议,需要转成字符串 AudioType
            audioProUp.setText(getAudioProtocolPostfix(sendAudioInfo));
            // 音频速率
            audioRateUp.setText(
                    String.format(Locale.ROOT, "%.2fk", sendAudioInfo.getRate() / 1000.00)); // 1966920, 1,966.92kbps
            // 音频丢包率[丢包数]  /10 %
            if (sendAudioInfo.getLostPackets() > 0) {
                audioLostrateUp.setText(sendAudioInfo.getLostPer() / 10.0 + "%[" + sendAudioInfo.getLostPackets()
                        + "]");
            } else {
                audioLostrateUp.setText(zeroValue);
            }
        }

        // 接收方 音频：
        RealAudioInfo recAudioInfo = callStatus.getRecAudioInfo();
        if (recAudioInfo != null) {
            // 音频协议,需要转成字符串 AudioType
            audioProDown.setText(getAudioProtocolPostfix(recAudioInfo));
            // 音频速率
            audioRateDown.setText(
                    String.format(Locale.ROOT, "%.2fk", recAudioInfo.getRate() / 1000.00)); // 1966920, 1,966.92kbps
            // 音频丢包率[丢包数]  /10 %
            if (recAudioInfo.getLostPackets() > 0) {
                audioLostrateDown.setText(
                        recAudioInfo.getLostPer() / 10.0 + "%[" + recAudioInfo.getLostPackets() + "]");
            } else {
                audioLostrateDown.setText(zeroValue);
            }
        }
    }

    private void updateAux() {
        // 发送方：
        RealVideoInfo sendAuxInfo = callStatus.getSendAuxInfo();
        if (sendAuxInfo != null) {
            // 材料丢包率[丢包数]  /10 %
            if (sendAuxInfo.getLostPackets() > 0) {
                auxLostrateUp.setText(sendAuxInfo.getLostPer() / 10.0 + "%[" + sendAuxInfo.getLostPackets() + "]");
            } else {
                auxLostrateUp.setText(zeroValue);
            }

            // 材料图像格式
            String auxForamtUp = getVideoProtocolPostfix(sendAuxInfo);
            conferenceAuxForamtUp.setText(auxForamtUp);
            if (auxForamtUp.length() > 13) {
                conferenceAuxForamtUp.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_30));
            } else {
                conferenceAuxForamtUp.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_35));
            }

            // 材料速率[帧率] // 1966920, 1,966.92kbps
            if (sendAuxInfo.getRate() == 0 && sendAuxInfo.getFps() == 0) {
                conferenceAuxRatetUp.setText(zeroValue);
            } else {
                conferenceAuxRatetUp.setText(
                        String.format(Locale.ROOT, "%.2fk", sendAuxInfo.getRate() / 1000.00) + " [" + sendAuxInfo.getFps()
                                + "]");
            }
        }

        // 接收方：
        RealVideoInfo recAuxInfo = callStatus.getRecAuxInfo();
        if (recAuxInfo != null) {
            // 材料丢包率[丢包数]  /10 %
            if (recAuxInfo.getLostPackets() > 0) {
                auxLostrateDown.setText(recAuxInfo.getLostPer() / 10.0 + "%[" + recAuxInfo.getLostPackets() + "]");
            } else {
                auxLostrateDown.setText(zeroValue);
            }

            // 材料图像格式
            String auxForamtDown = getVideoProtocolPostfix(recAuxInfo);
            conferenceAuxForamtDown.setText(auxForamtDown);
            if (auxForamtDown.length() > 13) {
                conferenceAuxForamtDown.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_30));
            } else {
                conferenceAuxForamtDown.setTextSize(TypedValue.COMPLEX_UNIT_PX,
                        mContext.getResources().getDimension(R.dimen.def_dimens_35));
            }

            // 材料速率[帧率] // 1966920, 1,966.92kbps
            if (recAuxInfo.getRate() == 0 && recAuxInfo.getFps() == 0) {
                conferenceAuxRatetDown.setText(zeroValue);
            } else {
                conferenceAuxRatetDown.setText(
                        String.format(Locale.ROOT, "%.2fk", recAuxInfo.getRate() / 1000.00) + " [" + recAuxInfo.getFps()
                                + "]");
            }
        }
    }

    /**
     * 处理视频协议
     *
     * @param videoInfo 视频流信息
     * @return result 视频流协议
     */
    private String getVideoProtocolPostfix(RealVideoInfo videoInfo) {
        String result = zeroValue;
        switch (videoInfo.getType()) {
            case H263:
                result = "H.263";
                break;
            case H264BP:
                result = "H.264BP";
                break;
            case H265:
                result = "H.265";
                break;
            case H264HP:
                result = "H.264HP";
                break;
            case H263PLUS:
                result = "H.263+";
                break;
            default:
                break;
        }
        if (videoInfo.getWidth() == 352 && videoInfo.getHeight() == 288) {
            result += " CIF";
        } else if (videoInfo.getWidth() == 1280 && videoInfo.getHeight() == 720) {
            result += " 720p";
        } else if (videoInfo.getWidth() == 1920 && videoInfo.getHeight() == 1080) {
            result += " 1080p";
        } else {
            if (videoInfo.getWidth() > 0 && videoInfo.getHeight() > 0) {
                result = result + " " + videoInfo.getWidth() + "x" + videoInfo.getHeight();
            }
        }
        return result.trim();
    }

    /**
     * 处理音频协议
     *
     * @param audioInfo 音频流信息
     * @return result 音频流协议
     */
    private String getAudioProtocolPostfix(RealAudioInfo audioInfo) {
        String result = zeroValue;
        switch (audioInfo.getType()) {
            case G711A:
                result = "G.711 A-Law";
                break;
            case G711U:
                result = "G.711 U-Law";
                break;
            case G722_48K:
                result = "G.722 48K";
                break;
            case G722_64K:
                result = "G.722 64K";
                break;
            case G7221C:
                result = "G.722.1C";
                break;
            case AAC_LD:
                if (audioInfo.getChannels() == 1) {
                    result = "AAC-LD MONO";
                } else if (audioInfo.getChannels() == 2) {
                    result = "AAC-LD STEREO";
                } else {
                    result = "AAC-LD";
                }
                break;
            case OPUS:
                result = "OPUS";
                break;
            case G729A:
                result = "G.729A";
                break;
            default:
                break;
        }
        return result;
    }

    public AdvMeetingInfoView(Context mContext) {
        super(mContext);
        init();
        registerListenerService();
    }

    private void init() {
        callStatus = MeetingManager.getInstance().getCallStatus();

        if (mRootView == null) {
            LogUtil.error( "initView error, mRootView is null");
            return;
        }
        // 返回
        back = mRootView.findViewById(R.id.adv_meeting_info_back);
        back.setOnClickListener(view -> clickBack());

        // 线路速率
        lineRateUp = mRootView.findViewById(R.id.linerate_context_up);
        lineRateDown = mRootView.findViewById(R.id.linerate_context_down);

        // 视频流图像格式
        mainpicFormatUp = mRootView.findViewById(R.id.mainpic_format_context_up);
        mainpicFormatDown = mRootView.findViewById(R.id.mainpic_format_context_down);

        // 视频速率[帧率]
        videoRateUp = mRootView.findViewById(R.id.videorate_context_up);
        videoRateDown = mRootView.findViewById(R.id.videorate_context_down);

        // 材料图像格式
        conferenceAuxForamtUp = mRootView.findViewById(R.id.conference_asspic_context_up);
        conferenceAuxForamtDown = mRootView.findViewById(R.id.conference_asspic_context_down);

        // 材料速率[帧率]
        conferenceAuxRatetUp = mRootView.findViewById(R.id.conference_auxrate_context_up);
        conferenceAuxRatetDown = mRootView.findViewById(R.id.conference_auxrate_context_down);

        // 音频协议
        audioProUp = mRootView.findViewById(R.id.audio_pro_context_up);
        audioProDown = mRootView.findViewById(R.id.audio_pro_context_down);

        // 音频速率
        audioRateUp = mRootView.findViewById(R.id.audiorate_context_up);
        audioRateDown = mRootView.findViewById(R.id.audiorate_context_down);

        // 视频丢包率[丢包数]
        videoLostrateUp = mRootView.findViewById(R.id.video_lostrate_context_up);
        videoLostrateDown = mRootView.findViewById(R.id.video_lostrate_context_down);

        // 材料丢包率[丢包数]
        auxLostrateUp = mRootView.findViewById(R.id.aux_lostrate_context_up);
        auxLostrateDown = mRootView.findViewById(R.id.aux_lostrate_context_down);

        // 音频丢包率[丢包数]
        audioLostrateUp = mRootView.findViewById(R.id.audio_lostrate_context_up);
        audioLostrateDown = mRootView.findViewById(R.id.audio_lostrate_context_down);

        // 入会时长
        confTime = mRootView.findViewById(R.id.conference_time_value);

        // 材料令牌
        auxToken = mRootView.findViewById(R.id.auxtoken);

        // 入会时长 单位是s
        confTime.setBase(SystemClock.elapsedRealtime() - callStatus.getJoinTime() * 1000);
        confTime.start();
    }

    private void clickBack() {
        BaseView baseView = ViewsFactory.getInstance().getBaseView(mContext, ViewNameConts.CONF_INFO_VIEW, false);
        if (baseView instanceof MeetingInfoView) {
            MeetingInfoView meetingInfoView = (MeetingInfoView) baseView;
            meetingInfoView.backToSetting();
            ViewsFactory.getInstance().removeView(ViewNameConts.ADV_CONF_INFO_VIEW);
            return;
        }
        LogUtil.info( "back fail.");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.adv_meeting_info;
    }

    @Override
    public void viewDataChanged(int eventId, Object obj) {
    }

    @Override
    public void unRegisterListenService() {
        stopTimer();
        confTime.stop();
    }

    @Override
    public void registerListenerService() {
    }
}
